package com.platform.modules.sys.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.platform.common.utils.Query;
import com.platform.modules.sys.dao.SysDeptDao;
import com.platform.modules.sys.entity.SysDeptEntity;
import com.platform.modules.sys.service.SysDeptService;

/**
 * @author 肖亮
 */
@Service("sysDeptService")
public class SysDeptServiceImpl extends ServiceImpl<SysDeptDao, SysDeptEntity> implements SysDeptService {

	
	@Autowired
	SysDeptDao sysDeptDao;
	
	@Override
	public IPage queryPage(Map<String, Object> params) {
		String key = (String) params.get("key");

		Page<SysDeptEntity> page = new Query<SysDeptEntity>(params).getPage();

		return baseMapper.selectPage(page,
				new QueryWrapper<SysDeptEntity>().like(StringUtils.isNotBlank(key), "USER_NAME", key).or()
						.like(StringUtils.isNotBlank(key), "OPERATION", key).orderByDesc("CREATE_TIME"));
	}

	  @Override
	    public boolean removeByIds(Collection<? extends Serializable> idList) {
	        return SqlHelper.delBool(baseMapper.deleteBatchIds(idList));
	    }
	
	
	@Override
	public boolean deleteBatch(String[] ids) {
		// TODO Auto-generated method stub
		return this.removeByIds(Arrays.asList(ids));
	}

	
	
	@Override
	public List<SysDeptEntity> getDeptTreeByOrgNo(String orgNo) {
		List<SysDeptEntity> list 
			= this.list(new QueryWrapper<SysDeptEntity>().eq("org_no",orgNo));
		
		
		//构建树状结构
		List<SysDeptEntity> trees = new ArrayList<SysDeptEntity>();
		Map<String, SysDeptEntity> map = list.stream().collect(
				Collectors.toMap(e->{
	                return e.getDeptId();
	            },e->{
	                return e;
	            })
			);
		for(SysDeptEntity v : list) {	
			String parentId = v.getParentId();
			if(parentId!=null) {
				SysDeptEntity node = map.get(parentId);
				if(node == null) {
					trees.add(v);
				}else {
					node.getChildren().add(v);
				}
			}else {
				trees.add(v);
			}
		}
		return trees;
	}

	
	@Override
	public boolean createRootDept(String name, String orgNo) {
		SysDeptEntity sysDeptEntity = new SysDeptEntity();
		sysDeptEntity.setName(name);
    	sysDeptEntity.setOrgNo(orgNo);
		return this.save(sysDeptEntity);
	}
}
